package org.zappee.dannyt.cairngorm.command
{
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	
	import mx.collections.ICollectionView;
	import mx.collections.IList;
	
	import org.zappee.dannyt.cairngorm.business.Bug;
	import org.zappee.dannyt.cairngorm.event.FilterBugsEvent;
	import org.zappee.dannyt.cairngorm.model.ModelLocator;
	
	public class FilterBugsCommand implements ICommand
	{
		public function FilterBugsCommand()
		{
		}
		
		private var showClosed:Boolean;
		private var filterText:String;
		
		public function execute(event:CairngormEvent):void
		{
			var filterBugsEvent:FilterBugsEvent = FilterBugsEvent(event);
			this.showClosed = filterBugsEvent.showClosed;
			this.filterText = filterBugsEvent.filterText;
			var model:ModelLocator = ModelLocator.getInstance();
			var tempBugs:ICollectionView = ICollectionView(model.bugs);
			tempBugs.filterFunction = filterBugs;
			tempBugs.refresh();
			model.bugs = IList(tempBugs);
		}
		
		private function filterBugs(bugItem:Object):Boolean
		{
			var filterFlag : Boolean = true;
			var bug:Bug = Bug(bugItem);
			
			if(!this.showClosed)
				filterFlag = bug.isOpen;
			if(this.filterText != "" && filterFlag)
				filterFlag = bug.Title.toLowerCase().indexOf(this.filterText.toLowerCase()) != -1 ? true : false;
			
			return filterFlag;
		}

	}
}